﻿using System;
using System.Threading;

namespace RxjhServer
{
	public class Lock : IDisposable
	{
		public static int DefaultMillisecondsTimeout = 1000;

		private object _obj;

		public Lock(object obj)
		{
			this.TryGet(obj, 1000, true, "");
		}

		public Lock(object obj, string lei)
		{
			this.TryGet(obj, 1000, true, lei);
		}

		public Lock(object obj, int millisecondsTimeout, bool throwTimeoutException, string lei)
		{
			this.TryGet(obj, millisecondsTimeout, throwTimeoutException, lei);
		}

		private void TryGet(object obj, int millisecondsTimeout, bool throwTimeoutException, string lei)
		{
			if (World.jlMsg == 1)
			{
				Form1.WriteLine(0, "TryGet");
			}
			if (Monitor.TryEnter(obj, millisecondsTimeout))
			{
				this._obj = obj;
				return;
			}
			if (throwTimeoutException)
			{
				Form1.WriteLine(1, string.Concat(new object[]
				{
					"锁定对象超时:",
					lei,
					" ",
					obj.GetType()
				}));
			}
		}

		public void Dispose()
		{
			if (this._obj != null)
			{
				Monitor.Exit(this._obj);
				this._obj = null;
			}
		}

		public bool IsTimeout
		{
			get
			{
				return this._obj == null;
			}
		}
	}
}
